<!-- 小区管理 -->
<template>
	<div class="app-container">
		<div class="wx-user-box">
			<div class="app-title">小区管理</div>
			<el-form :inline="true" :model="formInline" class="demo-form-inline">
				<el-form-item label="小区"><el-input v-model="formInline.name" clearable placeholder="请输入小区名称查询" @change="sousuo()"></el-input></el-form-item>
				<el-form-item label="物业公司">
					<el-select v-model="formInline.wuye_id" placeholder="请选择" clearable @change="sousuo()">
						<el-option :label="item.wy_name" :value="item.id" v-for="(item, index) in wuyeList" :key="index"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="时间筛选">
					<el-date-picker
						v-model="date"
						type="daterange"
						value-format="yyyy-MM-dd"
						range-separator="至"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
						@change="sousuo()"
					></el-date-picker>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="sousuo()" icon="el-icon-search">查询/筛选</el-button>
					<el-button type="primary" @click="Add()" icon="el-icon-circle-plus-outline">添加小区</el-button>
				</el-form-item>
				
			</el-form>

			<el-table :data="tableData" style="width: 100%">
				<!-- <el-table-column prop="id" label="小区ID"></el-table-column> -->
				<el-table-column prop="xq_name" label="小区名称"></el-table-column>
				<el-table-column prop="address" label="小区地址"></el-table-column>
				<el-table-column prop="wy_name" label="物业公司名称"></el-table-column>
				<el-table-column prop="createtime" label="创建时间"></el-table-column>
				<el-table-column label="状态">
					<template slot-scope="scope">
						<el-tag v-if="scope.row.state == 1">正常</el-tag>
						<el-tag v-else-if="scope.row.state == 2" type="info">关闭</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="搜索状态" width="100px">
					<template slot-scope="scope">
						<el-switch v-model="scope.row.allow_search == 1" @change="openShitch(scope.row.id,1)"></el-switch>
					</template>
				</el-table-column>
				<el-table-column label="停车异常通知" width="120px">
					<template slot-scope="scope">
						<el-switch v-model="scope.row.send_msg_flag_park == 1" @change="openShitch(scope.row.id,2)"></el-switch>
					</template>
				</el-table-column>
				<el-table-column label="操作" min-width="210px" align="center" fixed="right">
				    <template slot-scope="scope" style="display:flex">
						
							<el-button type="primary" plain size="mini" @click="setMallConfig(scope.row)">
							  商城平台扣点
							</el-button>
							<el-button type="warning" plain size="mini" @click="SetDate(scope.row)">
								修改
							</el-button>
							<el-button type="primary" plain size="mini" @click="refreshXiaoQuPrePayQrcode(scope.row)">
								更新预付出场码
							</el-button>
				     <!--   <el-button type="danger" plain size="mini" @click="del(scope.row)" icon="el-icon-delete">
				            删除
				        </el-button> -->
				    </template>
				</el-table-column>
			</el-table>
			<div class="el-pagination">
				<el-pagination
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="page"
					:page-sizes="[10, 100, 200, 300, 400]"
					:page-size="size"
					layout="total, sizes, prev, pager, next, jumper"
					:total="total"
				></el-pagination>
			</div>
		</div>
		
		<el-dialog :title="form.id ? '编辑小区' : '添加小区'" :visible.sync="centerDialogVisible" width="1000px" center
		    @close="reset('form')">
		    <div style="display: flex;position: relative;">
		        <div>
		            <el-form ref="form" style="width: 400px;" :rules="rules" :model="form" label-width="120px">
						<el-form-item prop="wuye_id" label="所属物业" >
							<el-select v-model="form.wuye_id" clearable placeholder="请选择" style="width: 80%" :disabled="form.id ? true : false">
								<el-option  :label="item.wy_name" :value="item.id" v-for="(item, index) in wuyeList" :key="index"></el-option>
							</el-select>
						</el-form-item>
		                <el-form-item prop="xq_name" label="小区名称">
		                    <el-input style="width: 80%" clearable v-model="form.xq_name" />
		                </el-form-item>
		                <el-form-item prop="address" label="小区地址">
		                    <el-input style="width: 80%" clearable v-model="form.address" />
		                </el-form-item>
		                <el-form-item prop="lngLat" label="经纬度">
		                    <div class="">
		                        <el-input style="width: 80%" clearable v-model="form.lngLat" />
		                        <div style="color: red">* 格式为:121.336050,31.150960</div>
		                        <div style="color: #2196f3; padding-left: 10px">点击右侧地图获取坐标</div>
		                    </div>
		                </el-form-item>
		
		            </el-form>
		            <div slot="footer" class="dialog-footer">
		                <div class="flex-center">
		                    <el-button @click="reset('form')">取 消</el-button>
		                    <el-button type="primary" @click="submit('form')">保 存</el-button>
		                </div>
		            </div>
		        </div>
		        <div id="container" style="width:500px;height:500px;"></div>
		        <div
		            style="position: absolute;top: 10px;right: 60px;background: #fff;border-radius: 6px;padding: 10px;">
		            <div id="myPageTop">
		                <table>
		                    <tr>
		                        <td>
		                            <label>请输入关键字：</label>
		                        </td>
		                    </tr>
		                    <tr>
		                        <td>
		                            <input
		                                style="padding:8px 10px;border-radius: 6px;border:1px solid #eee;margin-top: 5px;"
		                                id="tipinput" />
		                        </td>
		                    </tr>
		                </table>
		            </div>
		        </div>
		    </div>
		</el-dialog>
		
		<!-- 设置商城平台扣点 -->
		<el-dialog title="商城平台扣点" :visible.sync="centerDialogVisible2" width="540px" center @close="handleClose2">
			<el-form :model="form2" ref="ruleForm2" class="demo-form-inline" label-width="80px">
				<el-form-item label="小区名称">
					<el-input v-model="form2.xq_name" :disabled="true"></el-input>
				</el-form-item>
				<el-form-item label="平台扣点">
					<el-input v-model="form2.platform_deduction" :min="2" :max="100" clearable placeholder="请输入平台扣点" type="number"></el-input>
					<span style="color: #F56C6C;font-size: 13px;">扣点设置范围2~100</span>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="handleClose2">关闭</el-button>
				<el-button type="primary" @click="submitForm2('ruleForm2')">确定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import Api from '@/api/pages/wuye/house.js';
import wuyeApi from '@/api/pages/wuye/wuye.js';
import { checkNumber } from '@/utils/validate.js'
export default {
	name: 'house-list',
	data() {
		return {
			centerDialogVisible: false,
			centerDialogVisible2: false,
			formInline: {
				name: '',
				wuye_id: '',
				start_time: '',
				end_time: ''
			},
			form: {
			    xq_name: "",
				wuye_id: '',
			    name: "",
			    address: "",
			    lngLat: "",
			    levels: [{ level: 1, name: '' }],
			},
			form2:{
				xq_id: '',
				xq_name:'',
				platform_deduction:'',
			},
			rules: {
				wuye_id: [
				    {
				        required: true,
				        message: "请选择所属物业",
				        trigger: "change",
				    },
				],
			    xq_name: [
			        {
			            required: true,
			            message: "请输入小区名称",
			            trigger: "change",
			        },
			    ],
			    lngLat: [
			        {
			            required: true,
			            message: "请输入经纬度",
			            trigger: "change",
			        },
			    ],
			    address: [
			        {
			            required: true,
			            message: "请输入小区地址",
			            trigger: "change",
			        },
			    ],
			},
			page: 1,
			size: 10,
			total: 0,
			date: [],
			tableData: [],
			wuyeList: [],
			xq_longitude: '',
			xq_latitude: '',
		};
	},
	mounted() {
		this.getData();
		this.getWuyeList();
	},
	methods: {
		//打开关联
		setMallConfig(data){
			this.centerDialogVisible2=true;
			this.form2={
				xq_id: data.id,
				xq_name: data.xq_name,
				platform_deduction: data.mall_platform_deduction
			}
		},
		
		submitForm2(){
			if(!this.form2.platform_deduction){
				this.$message.error("请输入平台扣点");
				return;
			}
			if(this.form2.platform_deduction<2){
				this.$message.error("平台扣点不能小于2");
				return;
			}
			if(this.form2.platform_deduction>100){
				this.$message.error("平台扣点不能大于100");
				return;
			}
			let data={
				id:this.form2.xq_id,
				platform_deduction:this.form2.platform_deduction
			}
			// console.log(data)
			Api.updMallConfig(data).then(res => {
				if (res.state) {
					this.$message({
					  message: res.msg,
					  type: 'success'
					});
					this.getData();
					this.handleClose2();
				} else {
					this.$message(res.msg);
				}
			});
		},
		
		handleClose2(){
			this.centerDialogVisible2=false;
			this.form2={
				wuye_id: '',
				xq_name:'',
				platform_deduction:''
			}
		},
		
		// 地图初始化
		initMap: function () {
			let lng = String(this.xq_longitude)||'121.429876';
		    let lat = String(this.xq_latitude)||'31.153222';
		    // console.log('this.lat===' + lat, 'String(this.lng)-----' + lng)
		
		    var map = new AMap.Map("container", {
		        center: [lng,lat],
		        zoom: 13,
		        resizeEnable: true
		    });
		    let that = this;
		
		    if (lat) {
		        that.marker = new AMap.Marker({
		            position: new AMap.LngLat(lng,lat),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
		        });
		        // 将创建的点标记添加到已有的地图实例：
		        map.add(that.marker);
		        that.$forceUpdate();
		    }
		
		    //为地图注册click事件获取鼠标点击出的经纬度坐标
		    var clickEventListener = map.on('click', function (e) {
		        // console.log(e.lnglat.getLng())
		        // console.log(e.lnglat.getLat())
		        that.xq_longitude = e.lnglat.getLng();
		        that.xq_latitude = e.lnglat.getLat();
		        that.form.lngLat = that.xq_longitude+ ',' + that.xq_latitude;
		        // console.log(that.form.lngLat)
		        that.$forceUpdate();
		        if (that.marker) {
		            // 移除已创建的 marker
		            map.remove(that.marker);
		        }
		        that.marker = new AMap.Marker({
		            position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
		        });
		        // 将创建的点标记添加到已有的地图实例：
		        map.add(that.marker);
		    });
		    var autoOptions = {
		        input: "tipinput"
		    };
		    AMap.plugin(['AMap.PlaceSearch', 'AMap.AutoComplete'], function () {
		        // console.log('------')
		        var auto = new AMap.AutoComplete(autoOptions);
		        var placeSearch = new AMap.PlaceSearch({
		            map: map
		        });  //构造地点查询类
		        auto.on("select", select);//注册监听，当选中某条记录时会触发
		        function select(e) {
		            placeSearch.setCity(e.poi.adcode);
		            placeSearch.search(e.poi.name);  //关键字查询查询
		            if (e.poi.location) {
		                that.form.lngLat = e.poi.location.lng+ ',' + e.poi.location.lat;
		                // console.log(that.form.lngLat)
		                if (that.marker) {
		                    // 移除已创建的 marker
		                    map.remove(that.marker);
		                }
		                that.marker = new AMap.Marker({
		                    position: new AMap.LngLat(e.poi.location.lng, e.poi.location.lat),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
		                });
		                // 将创建的点标记添加到已有的地图实例：
		                map.add(that.marker);
		                that.$forceUpdate();
		            }
		        }
		    });
		},
		
		// 获取数据
		getData() {
			let data = {
				pageNumber: this.page,
				pageSize: this.size
			};
			if (this.formInline.name) {
				data['name'] = this.formInline.name.trim();
			}
			if (this.formInline.wuye_id) {
				data['wuye_id'] = this.formInline.wuye_id;
			}
			if (this.date && this.date.length) {
				data['start_time'] = this.date[0];
				data['end_time'] = this.date[1];
			}
			Api.query(data).then(res => {
				if (res.state) {
					this.tableData = res.data.list;
					this.total = res.data.totalRow;
				} else {
					this.$message(res.msg);
				}
			});
		},
		
		// 获取物业公司
		getWuyeList() {
			wuyeApi.getWuyeList().then(res => {
				if (res.state) {
					this.wuyeList = res.data;
				} else {
					this.$message(res.msg);
				}
			});
		},
		
		// 打开修改搜索状态询问
		openShitch(id,type=1) {
			let text='';
			if(type==1){
				text='搜索';
			}else{
				text='停车异常通知';
			}
			this.$confirm('您确定对当前'+text+'状态进行修改吗?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					if(type==1){
						this.upallow(id);
					}else{
						this.updateParkFlag(id);
					}
				})
				.catch(() => {});
		},
		
		// 修改搜索状态
		upallow(id) {
			Api.upallow({
				xiaoqu_id: id
			}).then(res => {
				if (res.state) {
					this.$message({
					  message: res.msg,
					  type: 'success'
					});
				} else {
					this.$message(res.msg);
				}
				this.getData();
			});
		},
		
		// 修改停车异常通知状态
		updateParkFlag(id) {
			Api.updateParkFlag({
				xiaoqu_id: id
			}).then(res => {
				if (res.state) {
					this.$message({
					  message: res.msg,
					  type: 'success'
					});
				} else {
					this.$message(res.msg);
				}
				this.getData();
			});
		},
		
		// 添加
		Add() {
			this.getWuyeList();
		    this.centerDialogVisible = true;
			this.$nextTick(()=>{
				this.initMap();
			})
		},
		// 更新预付出场码
		refreshXiaoQuPrePayQrcode(item) {
			let datas = {};
			datas["xq.id"]=item.id;
			datas["wuye_id"]=item.wuye_id;
			Api.refreshXiaoQuPrePayQrcode(datas).then((res) => {
				if (res.state) {
					this.$message({
						message: res.msg,
						type: "success",
					});
				} else {
					this.$message.error(res.msg);
				}
			});
		},
		
		// 编辑
		SetDate(item) {
			this.getWuyeList();
			item = JSON.parse(JSON.stringify(item));
		    this.form = Object.assign(this.form,item);
		    this.form.levels = [{ level: 1, name: '' }],
		    this.form.lngLat = item.xq_longitude + ',' + item.xq_latitude
		    this.xq_latitude = item.xq_latitude;
		    this.xq_longitude = item.xq_longitude;
		    this.centerDialogVisible = true;
		    this.$nextTick(()=>{
		    	this.initMap();
		    })
		},
		
		//保存
		submit(formName) {
			this.$refs[formName].validate((valid) => {
				if(valid){
					if (this.form.lngLat.indexOf(",") == -1) {
					    this.$message.error("小区经纬度格式不正确");
					    return;
					}
					if (!this.form.lngLat.split(",")[0] || !this.form.lngLat.split(",")[1]) {
					    this.$message.error("小区经纬度格式不正确");
					    return;
					}
					if (!checkNumber(this.form.lngLat.split(",")[0]) ||!checkNumber(this.form.lngLat.split(",")[1])) {
					    this.$message.error("小区经纬度格式不正确");
					    return;
					}
					let datas = {
						"wuye_id":this.form.wuye_id,
					    "xq.id": this.form.id || '',
					    "xq.xq_name": this.form.xq_name,
					    "xq.address": this.form.address,
					    "xq.xq_longitude": this.form.lngLat.split(",")[0],
					    "xq.xq_latitude": this.form.lngLat.split(",")[1],
					};
					// console.log(datas)
					Api.save(datas).then((res) => {
					    if (res.state) {
					        this.reset('form');
					        this.$message({
					            message: res.msg,
					            type: "success",
					        });
					        this.getData();
					    } else {
					        this.$message.error(res.msg);
					    }
					});
				}
			})
		    
		},
		
		// 重置
		reset(formName) {
		    this.$refs[formName].resetFields();
		    this.centerDialogVisible = false;
			this.xq_latitude = '';
			this.xq_longitude = '';
		    this.form = {
				wuye_id: "",
		        xq_name: "",
		        address: "",
		        name: "",
		        lngLat: "",
		        levels: [{ level: 1, name: '' }],
		    };
		},
		
		sousuo() {
			this.page = 1;
			this.getData();
		},
		handleSizeChange(val) {
			this.size = val;
			this.getData();
		},
		handleCurrentChange(val) {
			this.page = val;
			this.getData();
		},
	
	}
};
</script>
<style lang="scss" scoped></style>

<style lang="scss">
.amap-sug-result{
	z-index: 9999;
}
.dialogVideo {
	.el-dialog__body {
		padding: 20px;
	}
}
</style>
